package il.ac.tau.dbcourse.freedb;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FreeDbFileReader {
	class KeyValue {
		String key;
		StringBuilder value;
		
		public KeyValue(String key, String value) {
			this.key = key;
			this.value = new StringBuilder(value);
		}
		
		public String getKey() {
			return key;
		}
		
		public String getValue() {
			return value.toString();
		}
		
		public void setKey(String key) {
			this.key = key;
		}
		
		public void setValue(String value) {
			this.value = new StringBuilder(value);
		}
		
		public void appendValue(String suffix) {
			value.append(suffix);
		}
	}

	private BufferedReader br;
	private String queue = null;
	private boolean hadErrors = false;
	public long readLineTime = 0;
	
	public FreeDbFileReader(BufferedReader br, String queue) {
		this.br = br;
		this.queue = queue;	
	}
	
	public boolean hadErrors() {		
		return hadErrors;
	}
	
	private String readLine() throws IOException {
		long st = System.nanoTime(); 
		if (queue != null) {
			String ret = queue;
			queue = null;			
			return ret;
		}
		
		String line = br.readLine();
		
		readLineTime += System.nanoTime() - st;
		return line;
	}
	
	public void close() throws IOException {
		br.close();
	}
	
	public static byte splitPair(String s, String[] result) {
		StringTokenizer tokenizer = new StringTokenizer(s, "=");
		
		if (!tokenizer.hasMoreElements()) {
			result[0] = s;
			result[1] = "";
			return 0;
		}
		
		result[0] = tokenizer.nextToken();
		
		if (!tokenizer.hasMoreElements()) {
			result[1] = "";
			return 1;
		}
		
		result[1] = tokenizer.nextToken();
		return 2;
	}
	
	public KeyValue readPair() throws Exception {		
		String line = readLine();
		
		if (line == null)
			return null;
					
		String[] fields = new String[2];
		if (splitPair(line, fields) == 0) {
			System.out.println("Not a key-value pair (" + line + ")");
			hadErrors = true;
			return null;
		}
		
		KeyValue keyValue = new KeyValue(fields[0], fields[1]);
		
		while (true) {
			line = readLine();
			
			if (line == null)
				break;
			
			if (splitPair(line, fields) == 0) {
				System.out.println("Not a key-value pair (" + line + ")");
				hadErrors = true;
				return null;
			}
			
			if (!keyValue.getKey().equals(fields[0])) {
				queue = line; // Push this line back into the queue so it'll be used again later
				break;
			}
			
			keyValue.appendValue(fields[1]);
		}
		
		return keyValue;
	}
}
